<?php

namespace CuiFox\yii\db;

use Yii;
use CuiFox\yii\behaviors\SoftDeleteBehavior;
use CuiFox\yii\behaviors\TimestampBehavior;
use yii\caching\TagDependency;

class ActiveRecord extends \yii\db\ActiveRecord
{
    /**
     * @return array
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::class,
                'onCreate' => ['created_at', 'updated_at'],
                'onUpdate' => ['updated_at'],
            ],
            /*'softDelete' => [
                'class' => SoftDeleteBehavior::class,
                'timeAttribute' => true,
                'statusAttribute' => 'deleted_at',
            ],*/
        ];
    }

    /**
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     * @throws \yii\base\InvalidConfigException
     */
    public static function findFromCache($id)
    {
        return self::find()->where([
            self::primaryKey()[0] ?? 'id' => $id,
        ])->cache(true, new TagDependency([
            'tags' => self::getCacheKey($id),
        ]))->asArray()->one();
    }

    /**
     * @param $id
     * @return string
     * @throws \yii\base\InvalidConfigException
     */
    public static function getCacheKey($id)
    {
        return md5(json_encode([
            'tableName' => self::getTableSchema()->name,
            'primaryKey' => self::primaryKey()[0] ?? 'id',
            'id' => $id,
        ]));
    }

    /**
     * @param $id
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
    public static function deleteCache($id)
    {
        foreach ((array)$id as $it) {
            TagDependency::invalidate(Yii::$app->cache, self::getCacheKey($it));
        }
        return true;
    }
}